/**
 * 给指定的targetTable添加基于sortedTableModel的排序功能。
 * 
 * @param targetTable
 *            目标table的DOM对象
 * @param sortedTableBehavior
 *            见最下面的DefaultSortedTableModel定义
 */
SortedTable = function(targetTable, sortedTableBehavior) {
	var thisObject = this;
	sortedTableBehavior = sortedTableBehavior ? sortedTableBehavior : new DefaultSortedTableBehavior();
	var sortColumnIndex = -1;
	var sortType = undefined;

	/**
	 * 升序常量
	 */
	this.SORT_ASC = "SORT_ASC";
	/**
	 * 降序常量
	 */
	this.SORT_DESC = "SORT_DESC";

	var renderCell = function(cellObj) {
		// var img = Travian.travianDoc.createElement("img");
		// img.src = TrvnData.url.chromHome + "/images/blank.png";
		var span = Travian.travianDoc.createElement("span");
		span.innerHTML = '';
		cellObj.appendChild(span);
		cellObj.style.borderWidth = "1px";
		cellObj.style.borderStyle = "solid";
		cellObj.style.borderColor = "ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight";
		cellObj.style.cursor = "default";
		cellObj.addEventListener('click', function() {
			try {
				thisObject.sort(cellObj.cellIndex);
			} catch (e) {
				TrvnUtils.Logger.error("sorted-table.js 401: " + e);
			}
		}, false);
	};

	var initTableHeaders = function() {
		if (!targetTable.tHead) {
			return;
		}
		var cells = targetTable.tHead.rows[0].cells;
		for (var i = 0;i < cells.length; i++) {
			if (sortedTableBehavior.isColumnSortable && !sortedTableBehavior.isColumnSortable(i)) {
				continue;
			}
			renderCell(cells[i]);
		}
	};

	var updateTableHeaders = function() {
		if (!targetTable.tHead) {
			return;
		}
		var cells = targetTable.tHead.rows[0].cells;
		for (var i = 0;i < cells.length; i++) {
			if (sortColumnIndex == i && sortType) {
				cells[i].lastChild.innerHTML = sortType == thisObject.SORT_ASC ? '▲' : '▼';
				// cells[i].lastChild.src = sortType == thisObject.SORT_ASC ?
				// TrvnData.url.chromHome
				// + "/images/upsimple.png" : TrvnData.url.chromHome +
				// "/images/downsimple.png";
				// cells[i].lastChild.className = sortType==thisObject.SORT_ASC
				// ? "ascending" : "descending";
			} else {
				// cells[i].lastChild.src = TrvnData.url.chromHome +
				// "/images/blank.png";
				// cells[i].lastChild.className = "";
				cells[i].lastChild.innerHTML = '';
			}
		}
	};

	var getTableDataAt = function(columnIndex) {
		var data = [];
		var rows = targetTable.tBodies[0].rows;
		for (var i = 0;i < rows.length; i++) {
			data.push( {
				value : sortedTableBehavior.getSortableValueAt(rows[i], rows[i].cells[columnIndex]),
				rowObj : rows[i],
				toString : function() {
					return this.value;
				}
			});
		}
		return data;
	};

	var getComparator = function(columnIndex) {
		return compare = function(o1, o2) {
			if (sortedTableBehavior.getColumnComparator) return sortedTableBehavior.getColumnComparator(columnIndex).compare(o1.value, o2.value);
			else {
				if (o1.value < o2.value) return -1;
				if (o2.value < o1.value) return 1;
				return 0;
			}
		};
	};

	/**
	 * 将表格按第columnIndex列以type的方式排序
	 * 
	 * @param columnIndex
	 *            以0开始的表格列的索引
	 * @param type
	 *            排序方式，具体值见上面的常量定义
	 */
	this.sort = function(columnIndex, type) {
		if (type) {
			sortType = type;
		} else {
			if (sortColumnIndex != columnIndex) {
				sortType = thisObject.SORT_DESC;
			} else {
				sortType = sortType == thisObject.SORT_DESC ? thisObject.SORT_ASC : thisObject.SORT_DESC;
			}
		}
		var dataList = getTableDataAt(columnIndex);
		if (sortColumnIndex == columnIndex) {
			dataList.reverse();
		} else {
			dataList.sort(getComparator(columnIndex));
			if (sortType == thisObject.SORT_DESC) {
				dataList.reverse();
			}
		}
		var tBody = targetTable.tBodies[0];
		var nextSibling = tBody.nextSibling;
		targetTable.removeChild(tBody);
		dataList.each(function(data) {
			tBody.appendChild(data.rowObj);
		});
		targetTable.insertBefore(tBody, nextSibling);
		sortColumnIndex = columnIndex;
		updateTableHeaders();
		dataList = null;
	};

	initTableHeaders();
}

/**
 * 定义表格将以什么样的方式执行排序
 */
DefaultSortedTableBehavior = function() {
	/**
	 * 得到一个用于给第colIndex列排序的Comparator
	 * 
	 * @param colIndex
	 *            将根执行排序的列索引，0为第一列
	 * @return Comparator对象，请参见Colleciton.js中Comparator的定义
	 */
	this.getColumnComparator = function(colIndex) {
		this.compare = function(o1, o2) {
			if (o1 < o2) return -1;
			if (o2 < o1) return 1;
			return 0;
		};
		return this;
	};

	/**
	 * 得到行为rowObj列为cellObj中单元格中用于做排序的值
	 * 
	 * @param rowObj
	 *            DOM的tr对象
	 * @param cellObj
	 *            DOM的td对象
	 * @return 用于排序的值，该值将被传入Comparator中进行比较。
	 */
	this.getSortableValueAt = function(rowObj, cellObj) {
		return cellObj.innerHTML;
	};

	/**
	 * 指示第colIndex列是否需要排序的功能
	 * 
	 * @param colIndex
	 *            列索引
	 * @return 返回true则第colIndex可以排序，否则第colIndex列不能排序
	 */
	this.isColumnSortable = function(colIndex) {
		return true;
	};
}